<?php
namespace app\api\controller;
use think\Controller;
use wx\GetAccessToken;
use app\api\model\Userinfo as Userinfos;
use think\View;
use think\Request;
use think\Cache;
use think\Exception;
use think\Loader;
/**
 * 
 * @author sj
 *我的信息
 */
class Userinfo extends Co{
    
    private  static $UserModel;
    protected $beforeActionList = [
               'first'
       ];
    public function first(){
        if(!self::$UserModel){
            self::$UserModel=new Userinfos();
        }
        //echo "ss";
        if(empty(Cache::get('token')))
        {
            $appid=config('w_appkey');
            $appsecret=config('w_appsecret');
            $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
            $AcessToken=new \wx\GetAccessToken($url);
            try {
                $data=$AcessToken->https_request();
                $dataObj=json_decode($data);
                $access_token=$dataObj->access_token;
                Cache::set('token', $access_token,7200);
                 
            }catch (Exception $e){
                print ($e->getMessage());
            }
        
             
        
        }
    }
    
   
    public function selectUserInfo(){
//         $code=empty(input('get.code'))?ajaxReturn2(-1,'code is miss',''):input('get.code');
//         $res=$this->getAccess_token($code);
//         dump($res);
//         $access_token=$res['access_token"'];
//         $openId=$res['openid'];
        
       //$result=$this->getUserInfo($access_token, $openId);
       //session('user_id',1);
       $user_id=session('user_id');//这里测试
       $access_token=empty(input('get.access_token'))?session('access_token'):input('get.access_token');
       $openId=empty(input('get.openid'))?session('openid'):input('get.openid');
       $result=$this->getUserInfo($access_token, $openId);
       //dump($result);
       //$result=quotReg2($result);
      //var_dump($result);
      $r=self::$UserModel->selectUserInfo($user_id);
      //dump($r);
     if(empty($r)){
         $result['uid']=$user_id;
         self::$UserModel->add($result);
         return view('info',array('data'=>$result));
     }else{
         return view('info',array('data'=>$r));
     }
     
       
    }
    public function selectUserInfo2(){
        //$code=empty(input('get.code'))?ajaxReturn2(-1,'code is miss',''):input('get.code');
        //$res=$this->getAccess_token($code);
        //$access_token=$res['access_token"'];
        $user_id=session('user_id');//这里测试
       // echo $user_id;
        $r=self::$UserModel->selectUserInfo($user_id);
       
        //session('user_id',1);
       
         
      
        //dump($r);
       // dump($result);
        if(empty($r)){
            $openId=empty(input('get.openid'))?ajaxReturn2(-1,'openid is miss','sb'):input('get.openid');
            $access_token=Cache::get('token');
            //echo $access_token;
            $result=$this->getUserInfo2($access_token,$openId);
            $result['uid']=$user_id;
            self::$UserModel->add($result);
            return view('info',array('data'=>$result));
        }else{
            return view('info',array('data'=>$r));
        }
         
         
    }
    public function getAccess_token($code){
        $appid=config('w_appkey');
      
        $secret=config('w_appsecret');
        $url=" https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
        $wx=new GetAccessToken($url);
        $res=$wx->get_token();
       return json_decode($res,true);
    }
    public function getUserInfo($access_token,$openId){
        try {
            $url="https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openId&lang=zh_CN";
            $wx=new GetAccessToken($url);
            $res=$wx->get_token();
            return json_decode($res,true);
        }catch (\think\Exception $e){
            trace('select failed'.$e->getMessage());
        }
    }
    public function test(){
     return view('1',['data'=>array('sex'=>'1')]);
    }
    public function editPssword(){
        if(Request::instance()->isPost()){
            $post_date=input('post.');
            self::$UserModel->editPassword($post_date);
        }
      
    }
    public function  editPasswordByCode(User $user){
        if (Request::instance()->isPost()){
            $post_data=input('post.');
            $res=$user->checkTextValidateCode($post_data['telphone'],$post_data['code']);
          if($res){
              $re=self::$UserModel->editPasswordByCode($post_data);
              if($re){
                  ajaxReturn2(1,'edit sucess','');
              }else{
                  ajaxReturn2(0,'edit failed','');
              }
          }else{
              ajaxReturn2(0,'please fill contrrect code',$post_data);
          }
        }
    }
    public function t(){
        $where=['user_id'=>1,'oldpassword'=>'122223','newpassword'=>'1222223'];
        self::$UserModel->editPassword($where);
     
    }
    public function editPhoneByCode(User $user){
        if(Request::instance()->isPost()){
            $post_data=input('post.');
            $res=$user->checkTextValidateCode($post_data['telphone'],$post_data['code']);
            if($res){
                //如果输入的短信验证码正确 就不要让它输入在我的个人信息取出来 一个完整的数据绑定即可
                //如果手机号 uid 短信验证成功跳转页面
                return view('');
            }else {
                ajaxReturn2(0,'code is error',$post_data);
            }
            
        }
    }
    public function editPhoneByNew(User $user){
        if(Request::instance()->isPost()){
            $post_data=input('post.');
            //post中uid 
            $res=$user->checkTextValidateCode($post_data['newtelphone'],$post_data['code']);
            if($res){
                $r=self::$UserModel->editTelphone($post_data);
                if($r){
                    ajaxReturn2(1,'edit telphone sucess','');
                }else{
                    ajaxReturn2(0,'edit telphone failed','');
                }
            }
        }
    }
    /*
     * 根据openid查询用户信息 调用的是网页授权 
     * 调用微信公众号关注得到用户信息接口
     */
public function getUserInfo2($access_token,$openId){
        try {
          
            //echo $access_token;
            $url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openId&lang=zh_CN";
            $wx=new GetAccessToken($url);
            $res=$wx->get_token();
            return json_decode($res,true);
        }catch (\think\Exception $e){
            trace('select failed'.$e->getMessage());
        }
    }
    /**
     * 点击显示详情
     */
    public function getUserItems(){
       $id=session('user_id');//因为登录session状态
       $res=self::$UserModel->selectItem($id);
       //dump($res);
       return view('mod_info',array('data'=>$res));
       
    }
    public function updateinfo(){
        
        $user_id=session('user_id');
        $data=input('post.');
        $res=self::$UserModel->editinfo($user_id, $data);
        if($res){
            ajaxReturn2(1,'修改成功',url('getUserItems'));
        }else{
            ajaxReturn2(0,'修改失败',$data);
        }
    }
    //修改密码
    public function updatepassword(){
        $uid=session('user_id');
        if(Request::instance()->isGet()){
            return view('user2/modifyPwd');
        }else{
            $data=input('post.');
           
            $UserinfoValidate=Loader::validate('Userinfo');
            if(!$UserinfoValidate->check($data)){
                ajaxReturn2(-1,$UserinfoValidate->getError(),$data);
            }
            $oldpwd=$data['pwd'];
           $res=self::$UserModel->selectoldpwd($uid, $oldpwd);
           if(!$res){
               ajaxReturn2(100,'旧密码填写错误','');
           }
           $newpwd=$data['newpwd'];
           $r=self::$UserModel->selectoldpwd($uid, $newpwd);
           if($r){
               ajaxReturn2(200,'最近密码相同重新输入新密码','');
           }
           $qpwd=$data['qpwd'];
          $result= self::$UserModel->checkpwd($newpwd, $qpwd);
          if(!$result){
              ajaxReturn2(300,'俩次输入的密码不一样','');
          }
          
        $n=self::$UserModel->updatepwd($uid,$data);
        if($n){
            ajaxReturn2(1,'修改密码成功',url('api/userinfo/selectUserInfo2'));
        }else{
            ajaxReturn2(0,'修改失败','');
        }
            
        }
    }
    /**
     * 修改手机号
     */
    public function modphone(){
        $user_id=session('user_id');
        $telphone=self::$UserModel->selectphone($user_id)['telphone'];
        $qianwei=substr($telphone,0,3);
        $housiwei=substr($telphone,7,4);
        if(Request::instance()->isGet()){
            
            return view('mod_phone',array('data'=>array('qi'=>$qianwei,'hou'=>$housiwei,'tel'=>$telphone)));
        }
    }
    public function modphone2(){
       if(Request::instance()->isGet()){
           return view('mod_phone2');
       }else{
           $user_id=session('user_id');
           $code=input('post.code');
           $telphone=input('post.telphone');
           //检测验证码
           $Cvalidate=Loader::validate('Cvalidate');
           if(!$Cvalidate->check(input('post.'))){
               ajaxReturn2(-1,$Cvalidate->getError(),'');
           }
           
           $UserContr=controller('api/User');
           $res=$UserContr->checkTextValidateCode($telphone,$code);
           if(!$res){
               ajaxReturn2(0,'验证码填写错误','');
           }
           //下面验证手机号是否是新的手机号
          $res=self::$UserModel->checkphone($user_id, $telphone);
          if($res){
              ajaxReturn2(400,'请输入新的手机号',$telphone);
          }
          $r=self::$UserModel->updatephone($user_id, $telphone);
          if(!$r){
              ajaxReturn2(401,'修改失败','');
          }else{
              ajaxReturn2(200,'修改成功',url('selectuserinfo2'));
          }
           
       }
    }
    public function selectphone(){
        
    }
}